#include <stdio.h>
#include <stdlib.h>
#include "ULT.h"

struct threadNode{
  ThrdCtlBlk *thisNode;
 struct threadNode * nextNode;
};

struct linkedlist{
  int size;
  struct threadNode * headNode;
} ;

struct linkedlist *list_init(){
  struct linkedlist *list = (struct linkedlist *)malloc(sizeof(struct linkedlist));
  list->headNode = (struct threadNode *)malloc(sizeof(struct threadNode));
  list->size = 0;
  return list;
}

void append(struct linkedlist *list, ThrdCtlBlk *newnode){
  struct threadNode *headNode = list->headNode;
  int size = list->size;
  //printf("%d\n", size);
  if (list->size == 0){
    headNode->thisNode = newnode;
    list->size = 1;
  }
  else {
    struct threadNode *node;
    node = (struct threadNode *)malloc(sizeof(struct threadNode));
    node->thisNode = newnode;
    int i = 1;
    while (i < list->size){
      headNode = headNode->nextNode;
      i = i + 1;
    }
    headNode->nextNode = node;
    list->size = list->size + 1;
    return;
  }
}

void printlist(struct linkedlist *list){
  if (list->size == 0) { printf("NULL\n"); return; }
  struct threadNode *head = list->headNode;
  int i=1;
  while (i < list->size){
    printf("%d, ", head->thisNode->tid);
    head = head->nextNode;
    i = i+1;
  }
  printf("%d\n", head->thisNode->tid);
}

int pop(struct linkedlist *list){
  struct threadNode *head = list->headNode;
  int result = head->thisNode->tid;
  if (list->size == 1){
    free(head);
    list->headNode = (struct threadNode *)malloc(sizeof(struct threadNode));
    list->size = 0;
    return result;
  }
  list->headNode = head->nextNode;
  list->size = list->size - 1;
  free(head);
  return result;
  
}

void main() {
  ThrdCtlBlk *block;
  block->tid = 2;
  struct linkedlist *list = list_init();
  append(list,block);
  append(list,block);
  append(list,block);
  printlist(list);
  int popped = pop(list); 
  printlist(list);
  append(list,block);
  printlist(list);
  append(list,block);
  printlist(list);
  popped = pop(list);
  printlist(list);
  popped = pop(list);
  printlist(list);
  popped = pop(list);
  printlist(list);
  popped = pop(list);
  printlist(list);

}




